package com.easypan.component;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

// redis在项目这里的作用之一是：缓存一个邮箱的初始化内容
@Component("redisUtils")
public class RedisUtils<V> {

    @Resource
    private RedisTemplate<String, V> redisTemplate;
    public static final Logger logger = LoggerFactory.getLogger(RedisUtils.class);

    public V get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
//        return key == null ? null : (V) redisTemplate.boundValueOps(key).get(0,-1);
    }

    /***
     * 普通缓存放入
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key, V value){
        try{
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            logger.error("设置redisKey:{},value:{}失败",key,value);
            return false;
        }
    }

    /***
     * 普通缓存放入并设置过期时间
     * @param key
     * @param value
     * @param time
     * @return
     */
    public boolean setex(String key, V value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            logger.error("设置redisKey:{},value:{}失败",key,value);
            return false;
        }
    }

}
